<?php

class Adminarea_mods {

	private $addonsAll = array();
	private $addonsInstalled = array();
	private $addonsNotInstalled = array();

	public function init() {
		$this->getAddonsInfo();
		$this->route();
	}

	private function route() {
		if (isset($_GET['manage'])) {
			switch ($_GET['manage']) {
				case 'module':
					$this->manageModules();
					break;
				case 'plugin':
					$this->managePlugins();
					break;
				case 'editor':
					$this->manageEditors();
					break;
				default: die();
				break;
			}
		} else {
			$this->getAllList();
		}
	}

	private function managePlugins() {
		if (isset($_GET['activate'])) {
			$this->activate('plugin', $_GET['activate']);
		} elseif (isset($_GET['deactivate'])) {
			$this->deactivate('plugin', $_GET['deactivate']);
		} elseif (isset($_GET['export'])) {
			$this->export(MAINDIR . '/plugins/' . $_GET['export'] . '.php', 'plugin');
		} else {
			$this->pluginList();
		}
	}

	private function manageEditors() {
		if (isset($_GET['activate'])) {
			$this->activate('editor', $_GET['activate']);
		} elseif (isset($_GET['deactivate'])) {
			$this->deactivate('editor', $_GET['deactivate']);
		} elseif (isset($_GET['export'])) {
			$this->export(MAINDIR . '/editors/' . $_GET['export'] . '/', 'editor');
		} else {
			$this->editorList();
		}
	}

	private function editorList() {
		$table = Html::tr(
		Html::td(__('Назва'), 'chead', 'left', '18%') .
		Html::td(__('Опис'), 'chead', 'left', '45%') .
		Html::td(__('Статус'), 'chead', 'center', '10%') .
		Html::td(__('Дія'), 'chead', 'center', '27%')
		);

		foreach (array_merge($this->addonsInstalled['editors'], $this->addonsNotInstalled['editors']) as $editor) {


			$infXML = XMLParser::parseFile( MAINDIR . '/editors/' . $editor . '/info.xml');
			$infXML = $infXML['editor'];

			$info = array(
			'name' => $infXML['name'],
			'version' => $infXML['version'],
			'description' => $infXML['description']
			);

			$table .= $this->epRow($info, $editor, in_array($editor, $this->addonsInstalled['editors']));
		}
		Aurus::getInstance()->addContent(Html::table($table));
	}

	private function pluginList() {
		$table = Html::tr(
		Html::td(__('Назва'), 'chead', 'left', '18%') .
		Html::td(__('Опис'), 'chead', 'left', '45%') .
		Html::td(__('Статус'), 'chead', 'center', '10%') .
		Html::td(__('Дія'), 'chead', 'center', '27%')
		);

		foreach (array_merge($this->addonsInstalled['plugins'], $this->addonsNotInstalled['plugins']) as $plugin) {
			$pName = (substr(strtolower($plugin), -4) == '.php') ? substr($plugin, 0, -4) : $plugin;
			$pName = 'Plugin_' . $pName;
			$info = array(
			'name' => Factory::runStatic($pName, 'getName'),
			'version' => Factory::runStatic($pName, 'getVersion'),
			'description' => Factory::runStatic($pName, 'getDescription')
			);

			$table .= $this->pmRow($info, $plugin, in_array($plugin, $this->addonsInstalled['plugins']));
		}
		Aurus::getInstance()->addContent(Html::table($table));
	}

	private function pmRow($infoArray, $module, $isActive) {
		$ver = ($infoArray['version'] !== '') ? ' (v.' . $infoArray['version'] . ')' : '';
		$module = (substr(strtolower($module), -4) == '.php') ? substr($module, 0, -4) : $module;

		if ($isActive) {
			$actions = Html::tag(__('Відключити'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=plugin&amp;deactivate=' . $module)) . ' | ';
			$actions .= Html::tag(__('Налаштування'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=plugin&amp;options_page=' . $module)) . ' | ';
			$s = Html::tag(__('Увімкнено'), 'span', array('style' => 'color: green'));
		} else {
			$actions = Html::tag(__('Увімкнути'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=plugin&amp;activate=' . $module)) . ' | ';
			$s = Html::tag(__('Вимкнено'), 'span', array('style' => 'color: red'));
		}
		$actions .= Html::tag(__('Експорт'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=plugin&amp;export=' . $module));

		return Html::tr(
		Html::td($infoArray['name'], 'confclass', 'left', '18%') .
		Html::td($infoArray['description'], 'confclass', 'left', '45%') .
		Html::td($s, 'confclass', 'center', '10%') .
		Html::td($actions, 'confclass', 'center', '27%')
		);
	}

	//editor
	private function epRow($infoArray, $module, $isActive){
		$ver = ($infoArray['version'] !== '') ? ' (v.' . $infoArray['version'] . ')' : '';
		$module = (substr(strtolower($module), -4) == '.php') ? substr($module, 0, -4) : $module;

		if ($isActive) {
			$actions = Html::tag(__('Відключити'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=editor&amp;deactivate=' . $module)) . ' | ';
			$s = Html::tag(__('Увімкнено'), 'span', array('style' => 'color: green'));
		} else {
			$actions = Html::tag(__('Увімкнути'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=editor&amp;activate=' . $module)) . ' | ';
			$s = Html::tag(__('Вимкнено'), 'span', array('style' => 'color: red'));
		}
		$actions .= Html::tag(__('Експорт'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=editor&amp;export=' . $module));

		return Html::tr(
		Html::td($infoArray['name'], 'confclass', 'left', '18%') .
		Html::td($infoArray['description'], 'confclass', 'left', '45%') .
		Html::td($s, 'confclass', 'center', '10%') .
		Html::td($actions, 'confclass', 'center', '27%')
		);
	}

	private function activate($type, $name) {
		switch ($type) {
			case 'module':
				Factory::get('Module_' . $name)->onActivate();
				$n = $name;
				break;
				
			case 'plugin':
				Factory::runStatic('Plugin_' . $name,'onActivate');
				$n = $name.'.php';
				break;
			default: break;
		}
		Mysql::getInstance()->insert('modules', array('type' => $type, 'name' => $n));
		Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Додаток увімкнено')));
		Cache::clear();
	}

	private function deactivate($type, $name) {
		switch ($type) {
			case 'module':
				Factory::get('Module_' . $name)->onDeactivate();
				$n = $name;
				break;
			case 'plugin':
				$n = $name.'.php';
				Factory::runStatic('Plugin_' . $name,'onDeactivate');
				break;
			case 'editor':break;
			default: break;
		}

		Mysql::getInstance()->delete('modules', "type='{$type}' AND name='{$n}'");
		Aurus::getInstance()->addContent(Adminarea::getInstance()->adminInfo(__('Додаток вимкнено')));
		Cache::clear();
	}

	private function getAllList() {
		Aurus::getInstance()->addContent(
		Html::table(
		Html::tr(Html::td(' ', 'chead', 'left', '40%') .
		Html::td(__('Загальна кількість'), 'chead', 'left', '20%') .
		Html::td(__('Активовано'), 'chead', 'left', '20%') .
		Html::td(__('Не активовано'), 'chead', 'left', '20%')
		) .
		Html::tr(Html::td(Html::tag(__('Модулі'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=module')), 'confclass', 'left', '40%') .
		Html::td(count($this->addonsAll['modules']), 'confclass', 'left', '20%') .
		Html::td(count($this->addonsInstalled['modules']), 'confclass', 'left', '20%') .
		Html::td(count($this->addonsNotInstalled['modules']), 'confclass', 'left', '20%')
		) .
		Html::tr(Html::td(Html::tag(__('Плаґіни'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=plugin')), 'confclass', 'left', '40%') .
		Html::td(count($this->addonsAll['plugins']), 'confclass', 'left', '20%') .
		Html::td(count($this->addonsInstalled['plugins']), 'confclass', 'left', '20%') .
		Html::td(count($this->addonsNotInstalled['plugins']), 'confclass', 'left', '20%')
		) .
		Html::tr(Html::td(Html::tag(__('Редактори'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=editor')), 'confclass', 'left', '40%') .
		Html::td(count($this->addonsAll['editors']), 'confclass', 'left', '20%') .
		Html::td(count($this->addonsInstalled['editors']), 'confclass', 'left', '20%') .
		Html::td(count($this->addonsNotInstalled['editors']), 'confclass', 'left', '20%')
		)
		)
		);

		Aurus::getInstance()->addContent('<br /><a href="' . LINK_ROOT . 'adminarea/?do=mods&amp;action=recount">' . __('Оновити дані про додатки') . '</a>');
	}

	private function manageModules() {
		if (isset($_GET['activate'])) {
			$this->activate('module', $_GET['activate']);
		} elseif (isset($_GET['deactivate'])) {
			$this->deactivate('module', $_GET['deactivate']);
		} elseif (isset($_GET['export'])) {
			$this->export(MAINDIR . '/modules/' . $_GET['export'] . '/', 'module');
		} else {
			$this->modulesList();
		}
	}

	private function modulesList() {
		$table = Html::tr(
		Html::td(__('Назва'), 'chead', 'left', '18%') .
		Html::td(__('Опис'), 'chead', 'left', '52%') .
		Html::td(__('Автор'), 'chead', 'center', '10%') .
		Html::td(__('Статус'), 'chead', 'center', '10%') .
		Html::td(__('Дія'), 'chead', 'center', '20%')
		);

		foreach (array_merge($this->addonsInstalled['modules'], $this->addonsNotInstalled['modules']) as $module) {
			if (is_file(MAINDIR . '/modules/' . $module . '/info.xml')) {
				$info = XMLParser::parseFile(MAINDIR . '/modules/' . $module . '/info.xml');
				$info = $info['module'];
			} else {
				$info = array(
				'name' => $module,
				'version' => '',
				'module_url' => '',
				'author' => '',
				'author_url' => '',
				'description' => ''
				);
			}

			$table .= $this->mmRow($info, $module, in_array($module, $this->addonsInstalled['modules']));
		}
		Aurus::getInstance()->addContent(Html::table($table));
	}

	private function mmRow($infoArray, $module, $isActive) {
		$ver = ($infoArray['version'] !== '') ? ' (v.' . $infoArray['version'] . ')' : '';

		if ($isActive) {
			$actions = Html::tag(__('Відключити'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=module&amp;deactivate=' . $module)) . ' | ';
			$s = Html::tag(__('Увімкнено'), 'span', array('style' => 'color: green'));
		} else {
			$actions = Html::tag(__('Увімкнути'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=module&amp;activate=' . $module)) . ' | ';
			$s = Html::tag(__('Вимкнено'), 'span', array('style' => 'color: red'));
		}
		$actions .= Html::tag(__('Експорт'), 'a', array('href' => LINK_ROOT . 'adminarea/?do=mods&amp;manage=module&amp;export=' . $module));



		return Html::tr(
		Html::td($infoArray['name'] . $ver, 'confclass', 'left', '18%') .
		Html::td($infoArray['description'], 'confclass', 'left', '52%') .
		Html::td($infoArray['author'], 'confclass', 'center', '10%') .
		Html::td($s, 'confclass', 'center', '10%') .
		Html::td($actions, 'confclass', 'center', '20%')
		);
	}

	private function getAddonsInfo() {
		foreach (Mysql::getInstance()->select('modules') as $addon) {
			switch ($addon['type']) {
				case 'module':
					$this->addonsInstalled['modules'][] = $addon['name'];
					break;
				case 'editor':
					$this->addonsInstalled['editors'][] = $addon['name'];
					break;
				case 'plugin':
					$this->addonsInstalled['plugins'][] = $addon['name'];
					break;
			}
		}
		if  ( !isset($this->addonsInstalled['plugins'])) {
			$this->addonsInstalled['plugins'] = array();
		}
		if  ( !isset($this->addonsInstalled['modules'])) {
			$this->addonsInstalled['modules'] = array();
		}
		if  ( !isset($this->addonsInstalled['editors'])) {
			$this->addonsInstalled['editors'] = array();
		}

		//All plugins
		$this->addonsAll['plugins'] = read_directory(MAINDIR . '/plugins/', 0, 1, 'php');
		$this->addonsAll['editors'] = read_directory(MAINDIR . '/editors/', 1, 0);
		$this->addonsAll['modules'] = read_directory(MAINDIR . '/modules/', 1, 0);

		//not installed plugins
		$this->addonsNotInstalled['plugins'] = array_diff($this->addonsAll['plugins'], $this->addonsInstalled['plugins']);
		$this->addonsNotInstalled['plugins'] = array_values($this->addonsNotInstalled['plugins']);

		$this->addonsNotInstalled['editors'] = array_diff($this->addonsAll['editors'], $this->addonsInstalled['editors']);
		$this->addonsNotInstalled['editors'] = array_values($this->addonsNotInstalled['editors']);

		$this->addonsNotInstalled['modules'] = array_diff($this->addonsAll['modules'], $this->addonsInstalled['modules']);
		$this->addonsNotInstalled['modules'] = array_values($this->addonsNotInstalled['modules']);
	}

	private function export($path, $type) {
		$data = $this->getData($path, $type);
		$_data[$type] = $data;

		$exportData = XMLParser::array2xml($_data);
		FilesTransfer::getInstance()->fileDownloadFromContent($type.'_'.basename($path).'.xml',$exportData);
	}

	private function getData($path, $type) {
		$ret = array();

		if (is_dir($path)) {
			$files = read_directory($path, false, false, null, true, true);
			$pref = $path;
		} else {
			$files = array($path);
			$pref = '';
		}

		foreach ($files as $file) {

			if (is_dir($pref.$file)) {
				$ret[]['dir'] = array(
				'name' => basename($file),
				'perms' => getPerms($pref . $file),
				);
			} else {
				$ret[]['file'] = array(
				'dir' => '0',
				'name' => basename($file),
				'perms' => getPerms($pref.$file),
				'content' => base64_encode(file_get_contents($pref.$file))
				);
			}
		}

		return $ret;
	}

	private function getDirName($file, $type) {
		switch ($type) {
			case 'module':
				$ret = explode('modules', $file);
				return end($ret);
				break;
		}
	}

}
